/*
 * Copyright (c) 2017, 1DAOYUN and/or its affiliates. All rights reserved.
 * 1DAOYUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.iot.nev.gateway.connector.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import com.iot.nev.gateway.connector.Connector;
import com.iot.nev.gateway.utils.UtilTools;

/**
 * 
 * @author soongxueyong
 *
 */
public class MysqlConnector implements Connector {
	private static Properties mysqls = UtilTools.getConfig(System.getProperty("user.dir") + "/configuration/config.properties");
	private final String driver = mysqls.getProperty("mysql_driver");
	private final String url = mysqls.getProperty("mysql_url");
	private final String user = mysqls.getProperty("mysql_user");
	private final String password = mysqls.getProperty("mysql_password");
	private static Connection con;

	public Connection getConnection() {
		try {
			if (con == null) {
				// 加载驱动程序
				Class.forName(driver);
				// 1.getConnection()方法，连接MySQL数据库！！
				con = DriverManager.getConnection(url, user, password);
			}
			return con;
		} catch (ClassNotFoundException e) {
			// 数据库驱动类异常处理
			System.err.println("Sorry,can`t find the Driver!");
			e.printStackTrace();
		} catch (SQLException e) {
			// 数据库连接失败异常处理
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public void close() {
		try {
			if (con != null) {
				con.close();
				con = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
